package com.flag.liutao.modules.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flag.liutao.common.domain.LocalUser;
import com.flag.liutao.common.handler.MyException;
import com.flag.liutao.modules.user.domain.User;
import com.flag.liutao.modules.user.service.IUserService;
import com.flag.liutao.modules.user.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;

    /**
     * 认证成功后，从数据库中获取信息的方法
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUserName,userName);
        User user = userService.getOne(lqw);

        if(ObjectUtil.isNull(user)){
            throw new RuntimeException("该用户不存在");
        }

        List<String> list = userService.getAuthorities(user.getId());

        LocalUser localUser = new LocalUser(user,list);
        return localUser;
    }
}
